﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
namespace test14 {
    public class enemy : MonoBehaviour
    {
        private Rigidbody rb;//刚体
        private Vector3 targetPosition;//目标点
        private NavMeshAgent nav;//导航代理
        float dis=0.1f;//距离
        public bool isclick = false;//是否点击
        private MeshRenderer mesh;
        public Material[] color;//材质球数组
       // public LayerMask eney;
        private playercontroller player;//玩家
       
        // Start is called before the first frame update
        void Start()
        {
            rb = GetComponent<Rigidbody>();
            nav = GetComponent<NavMeshAgent>();
            mesh = GetComponent<MeshRenderer>();
            player = GameObject.Find("player").GetComponent<playercontroller>();
        }

        // Update is called once per frame
        void Update()
        {
           //如果目标点距离小于2改变目标点
            if (dis <= 2f)
                move();
            dis = Vector3.Distance(transform.position, targetPosition);
            procStop();
        }
        /// <summary>
        /// 判断是否被点击
        /// </summary>
        private void procStop()
        {
            if (isclick)
            {
                StartCoroutine(stop());
            }
        }
        /// <summary>
        /// 移动
        /// </summary>
        private void move()
        {
           
            float point_x = Random.Range(-7, 7);
            float point_z = Random.Range(-7, 7);
            targetPosition = new Vector3(point_x, 1, point_z);
            nav.SetDestination(targetPosition);
        }
       
        /// <summary>
        /// 停止移动
        /// </summary>
        /// <returns></returns>
        private IEnumerator stop()
        {
            nav.speed = 0;
            rb.velocity = Vector3.zero;
            mesh.material = color[0];
            yield return new WaitForSeconds(3);
            nav.speed = 2f;
            mesh.material = color[1];
            isclick = false;
        }
        /// <summary>
        /// 碰撞检测
        /// </summary>
        /// <param name="collision"></param>
        private void OnCollisionEnter(Collision collision)
        {
                if (collision.collider.CompareTag("Player"))
                {
                    if (nav.speed == 0)
                    {
                         Destroy(gameObject);
                         player.count--;
                     }
                }
        }
    }
}
